<template>
  <div>
    <div>
      <a-space align="start" v-if="!disabled">
        <a-textarea placeholder="请输入商户号，一行一个，每次最多输入500个" v-model="merchantNos" :disabled="hasUploaded || disabled" style="width: 200px" :rows="3"></a-textarea>
        <a-button type="primary" @click="getMerchants()">新增</a-button>
        <a-button type="primary" @click="importTemplate">导入</a-button>
        <a-button type="primary" @click="downloadTemplate">下载导入模板</a-button>
      </a-space>
    </div>
    <a-table :data-source="value" :columns="columns" :pagination="pagination" row-key="mchntNo" :filter-value="filterValue" size="small" style="background: #fff">
      <template v-slot:filterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }">
        <a-space>
          <a-input placeholder="请输入商户号" v-model="filterValue" style="width: 120px"
                   @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
                   v-ant-ref="c => (searchInput = c)"/>
          <a-button size="small" type="primary" @click="() => filter(selectedKeys, confirm, column.dataIndex)">筛选</a-button>
          <a-button size="small" type="primary" @click="() => reset(clearFilters)">重置</a-button>
        </a-space>
      </template>
      <template v-slot:operation="text, record, index" v-if="operatorType === 'add' || operatorType === 'edit'">
        <div style="white-space: nowrap">
          <a-button size="small" @click="del(record, index)" type="danger" v-if="!disabled">删除</a-button>
          <a-button size="small" @click="cancelDel(record, index)" type="danger" v-if="!disabled">取消删除</a-button>
        </div>
      </template>
    </a-table>
  </div>
</template>

<script>
export default {
  name: 'MerchantSelector',
  props: {
    checkedOrgInfo: {
      type: Array,
      default: () => []
    },
    disabled: {
      type: Boolean,
      default: false
    },
    value: {
      type: Array,
      default: () => []
    },
    hasUploaded: {
      type: Boolean,
      default: false
    },
    getMerchantsHandle: {
      type: Function
    },
  },
  computed: {
    orgInfo () {
      return this.checkedOrgInfo
    },
  },
  data() {
    return {
      filterValue: '',
      visible: false,
      form: {
        mchntNo: '',
      },
      labelCol: {span: 8},
      wrapperCol: {span: 16},
      merchantNos: '',
      searchInput: null,
      mrctFilePath: '',
      operatorType: 'add',
      columns: [
        {
          width: 250,
          title: "商户号",
          dataIndex: "mchntNo",
          scopedSlots: {
            filterDropdown: 'filterDropdown',
          },
          onFilter: (value, record) => record.mchntNo.toString().includes(value),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                this.searchInput.focus();
              });
            }
          },
        },
        {title: "商户名称", dataIndex: "mchntName",},
        {
          title: "状态",
          dataIndex: "mcStatus",
          customRender (text) {
            return text || "正常"
          }
        },
        {
          title: '操作',
          scopedSlots: {customRender: 'operation'}
        }
      ],
      pagination: {
        pageSizeOptions: ['5', '10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      },
    }
  },
  methods: {
    filter(selectedKeys, confirm, dataIndex) {
      this.filterValue = selectedKeys[0]
      confirm()
    },
    reset(clearFilters) {
      clearFilters();
      this.filterValue = '';
    },
    async getMerchants(merchantNos, fetchMerchants) {
      if (this.getMerchantsHandle) {
        this.getMerchantsHandle(...arguments)
      } else {
        if (this.hasUploaded) {
          this.$message.error('已经导入过商户号，不允许再手动添加！');
          return
        }
        if (this.orgInfo.length === 0) {
          this.$message.error('请先选择参与机构');
          return
        }
        if (!merchantNos && (!this.merchantNos || !this.merchantNos.trim())) {
          this.$message.error('请输入商户号！');
          return
        }
        let merchantList = (merchantNos || this.merchantNos).split('\n').filter(i => i.trim())
        if (merchantList.length > 500) {
          this.$message.error('最多输入500个商户号！');
          return
        }
        // 去重
        merchantList = [...new Set(merchantList)]
        // 与之前输入的商户号对比去重
        let oldMerchantList = this.value.map(i => i.mchntNo)
        merchantList = merchantList.filter(i => !oldMerchantList.includes(i))
        if (merchantList.length === 0) {
          this.merchantNos = ''
          this.$message.error('请输入新的商户号！');
          return
        }
        const hide = this.$message.loading('正在查询商户信息...', 0);
        try {
          let res
          if (fetchMerchants) {
            res = await fetchMerchants()
          } else {
            res = await this.$postJson('/admin/market/cashierManager/getMcList', {
              data: merchantList.join(','),
              selectedOrgInfoList: this.orgInfo
            })
          }
          if (res.data.code === '100000') {
            let successData = res.data.data.successData
            // 特殊费率的商户也可以添加
            const feeMchntObj = res.data.data.feeMchntData;
            if (feeMchntObj) {
              successData = successData.concat(feeMchntObj)
            }

            const errorData = res.data.data.errorData
            if (errorData && errorData.length > 0) {
              this.$notification.error({
                message: '提示',
                description: `商户号：${errorData.map(i => i.mchntNo).join(',')}存在错误，请重新输入！`,
                duration: 0
              });
            }
            const orgMchntData = res.data.data.orgMchntData;
            if (orgMchntData && orgMchntData.length > 0) {
              this.$notification.error({
                message: '提示',
                description: `商户号：${orgMchntData.map(i => i.mchntNo).join(',')}不符合要求，请重新输入！`,
                duration: 0
              });
            }
            if (successData.length) {
              let merchants = this.value
              merchants = merchants.concat(successData)
              this.$emit('input', merchants)
            }
            this.merchantNos = ''
          } else {
            this.$message.error(res.data.message);
          }
        } catch (e) {
          this.$message.error('获取商户失败');
          console.error(e)
        }
        hide()
      }
    },

    search() {
      this.pagination = Object.assign({} ,{
        current: 1,
        pageSize: 10
      })
      this.fetch();
    },
    del(record, index) {
      const merchants = this.value
      merchants.splice(index, 1, {
        ...record,
        mcStatus: '已删除',
        oprType: 'D'
      })
      this.$emit('change', merchants)
    },
    cancelDel(record, index) {
      const merchants = this.value
      merchants.splice(index, 1, {
        ...record,
        mcStatus: '',
        oprType: 'I'
      })
      this.$emit('change', merchants)
    },

    async downloadTemplate () {
      try {
        await this.$download('admin/market/cashierManager/getExcel?type=0',{}, 'mchntNoBatchImportTemplate.xls')
      } catch (e) {
        console.error(e)
      }
    },
    async importTemplate () {
      const formData = new FormData()
      if (this.orgInfo.length === 0) {
        this.$message.error('请选择参与机构')
        return
      }
      const fileInput = document.createElement('input')
      fileInput.type = 'file'
      fileInput.accept = '.xls,.xlsx'
      fileInput.onchange = async () => {
        const file = fileInput.files[0]
        if (!file) {
          this.$message.error('请选择文件')
          return
        }
        formData.append('excelFile', file)
        try {
          const res = await this.$upload('admin/market/cashierManager/upload', formData)
          if (res.data.code === '100000') {
            this.$message.success('导入成功')
            this.mrctFilePath = res.data.data
            this.$emit('uploaded', res.data.data)
          } else {
            this.$message.error(res.data.message)
          }
        } catch (e) {
          console.error(e)
          this.$message.error('导入失败')
        }
      }
      fileInput.click()
    },
  }
}
</script>

<style scoped>

</style>
